<%@ Page Language="C#" %>

<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>

<script runat="server">
	string errormessage;
	
	protected override void OnInit(EventArgs e)
	{
		base.OnInit(e);

		if (!IsLocalIP())
			return;

		try
		{
			Process();
		}
		catch (Exception x)
		{
			errormessage = x.ToString();
		}

		if (errormessage != null)
		{
			Response.Clear(); 
			Response.StatusCode = 500;
			Response.Write("Error:" + errormessage);
			Response.End();
		}
	}

	bool IsLocalIP()
	{
		string ip = Request.UserHostAddress;
		if (ip == "127.0.0.1")
			return true;
		if (ip == "::1")
			return true;

		string serverip = Request.ServerVariables["LOCAL_ADDR"];
		if (ip == serverip)
			return true;
	
		return false;
	}

	void Process()
	{
		string jobfile = Request.QueryString["job"];

		if (!File.Exists(jobfile))
		{
			errormessage = "Job file not found!" + jobfile;
			return;
		}

		if (!jobfile.EndsWith(".job.config"))
		{
			errormessage = "Job file does not ends with .job.config!" + jobfile;
			return;
		}

		string imagefile = jobfile.Substring(0, jobfile.Length - ".jog.config".Length);
		if (!File.Exists(imagefile))
		{
			errormessage = "Image file not found!" + jobfile;
			return;
		}

		XmlDocument doc = new XmlDocument();
		doc.Load(jobfile);
		if (doc.DocumentElement.Name != "GenerateThumbnail")
		{
			errormessage = "Job file root is not GenerateThumbnail!" + jobfile;
			return;
		}

		try
		{
			string imagepath = doc.DocumentElement.GetAttribute("ImagePath");
			string thumbpath = doc.DocumentElement.GetAttribute("ThumbPath");

			switch(Path.GetExtension(thumbpath).ToLower())
			{
				case ".jpeg":
				case ".jpg":
				case ".gif":
				case ".png":
					break;
				default:
					throw (new Exception("thunbnail must save to jpeg/jpg/gif/png"));
			}
			
			int thumbwidth = int.Parse(doc.DocumentElement.GetAttribute("ThumbWidth"));
			int thumbheight = int.Parse(doc.DocumentElement.GetAttribute("ThumbHeight"));

			string size = GenerateThumbnail(imagepath, thumbpath, thumbwidth, thumbheight);
			string[] sizepair = size.Split(',');

			doc.DocumentElement.SetAttribute("Width", sizepair[0]);
			doc.DocumentElement.SetAttribute("Height", sizepair[1]);
			doc.Save(jobfile);
		}
		catch (Exception x)
		{
			doc.DocumentElement.SetAttribute("Error", x.ToString());
			doc.Save(jobfile);
		}
		
	}
	public string GenerateThumbnail(string imagepath, string thumbpath, int thumbwidth, int thumbheight)
	{
		string sizeinfo;
		byte[] data;
		using (FileStream fs = new FileStream(imagepath, FileMode.Open, FileAccess.Read, FileShare.Read))
		{
			data = new byte[fs.Length];
			fs.Read(data, 0, data.Length);
		}
		using (System.Drawing.Image img = System.Drawing.Image.FromStream(new MemoryStream(data)))
		{
			sizeinfo = img.Width + "," + img.Height;

			double scale = Math.Min(((double)thumbwidth) / (double)img.Width, ((double)thumbheight) / (double)img.Height);
			int w = (int)Math.Floor(img.Width * scale);
			int h = (int)Math.Floor(img.Height * scale);

			using (System.Drawing.Image thumb = new System.Drawing.Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
			{
				using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(thumb))
				{
					g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

					g.DrawImage(img
						, new System.Drawing.Rectangle(-1, -1, w + 2, h + 2)
						, new System.Drawing.Rectangle(0, 0, img.Width, img.Height)
						, System.Drawing.GraphicsUnit.Pixel);

					thumb.Save(thumbpath);
				}
			}
		}

		return sizeinfo;
	}
</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
	<form id="form1" runat="server">
		<%=errormessage %>
	</form>
</body>
</html>
